package lime49.lockcrypt.mobile;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.midlet.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.obex.*;
import javax.microedition.lcdui.*;

public class BTClient {

    static final String serverUUID = "11111111121111111111212111111123";
    private Display display;
    private Form form;

    public BTClient(MIDlet parent, Form form) throws IOException {
        this.form = form;
        display = Display.getDisplay(parent);
        display.setCurrent(form);
        form.append("Starting...");
        LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
//btgoep://001842E7800A:9;authenticate=false;encrypt=false;master=false
        SessionNotifier serverConnection = (SessionNotifier) Connector.open("btgoep://localhost:"
                + serverUUID + ";name=ObexExample");
        int count = 0;
        while(count < 2) {
            RequestHandler handler = new RequestHandler();
            serverConnection.acceptAndOpen(handler);
            form.append("Received OBEX connection " + (++count));
            //System.out.println("Received OBEX connection " + (++count));
        }
    }

    private static class RequestHandler extends ServerRequestHandler {
        public int onPut(Operation op) {
            try {
                HeaderSet hs = op.getReceivedHeaders();
                String name = (String) hs.getHeader(HeaderSet.NAME);
                if (name != null) {
                    System.out.println("put name:" + name);
                }
                InputStream is = op.openInputStream();
                StringBuffer buf = new StringBuffer();
                int data;
                while ((data = is.read()) != -1) {
                    buf.append((char) data);
                }
                System.out.println("got:" + buf.toString());
                op.close();
                return ResponseCodes.OBEX_HTTP_OK;
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
            }
        }
    }
}